﻿using System;
using System.Collections.Generic;
using System.Threading;
using Com.AAS.Common.Basic;

namespace Com.AAS.Common.Queue
{
    public abstract class QueueHandler<T> : Working
    {
        private AutoResetEvent autoRestEvent = new AutoResetEvent(false);
        private Queue<T> queue = new Queue<T>(10 *  1024 * 1024 );

        public void Put(T item)
        {
            queue.Enqueue(item);
            autoRestEvent.Set();
        }

        public override void ToRun()
        {
            new Thread(new ThreadStart(() =>
            {
                // 等待队列正式启动
                while (!IsStart())
                {
                    try
                    {
                        Thread.Sleep(3 * 500);
                    }
                    catch (Exception e)
                    {
                    }
                }

                // 对来开始工作等待终止信号
                while (!IsStop())
                {
                    autoRestEvent.WaitOne();
                    while (queue.Count > 0)
                    {
                        T item = queue.Dequeue();
                        // 逐项处理内部的事件项
                        OnProcess(item);
                    }
                }
            })) { IsBackground = true }.Start();
        }

        protected abstract void OnProcess(T item);
    }
}
